//
// Timeline Controller
//
var ObjectID   = require('mongoose').Schema.Types.ObjectId;

module.exports = function(app) {

   // List timeline events for selected user
   app.route('/timelines/list/:id')
      .get(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         Domain.Timeline.find( {owner_id: id} ).exec( function(err, events){
            if(err) throw err;
           
            var new_events = [];
            for(var ev in events){
               //
               // mongoose doc to json object
               // define a schema.options.toJSON function inside timeline.schema.js
               //
               new_events.push( events[ev].toJSON() );
            } 

            res.render( 'timelines/list', { user: req.user, csrf: req.csrfToken(), events: new_events } );
         });
      })
      
      .post(app.isLoggedIn, function(req, res){
         var id = req.params.id;
         var event         = new Domain.Timeline();
         event.owner_id    = req.user._id.toString();
         event.title       = req.body.title;
         event.description = req.body.description;
         event.start       = req.body.start;
         event.end         = req.body.end;
         event.link        = req.body.link;
         event.image       = req.body.image;
         event.icon        = req.body.icon;
         event.color       = req.body.color;
         event.save(function(err){
            if(err) throw err
            res.redirect('/timelines/list/' + id);
         });
      });

};




